<?php
/*
Dar galima prideti
if (isset($_SERVER['HTTP_REFERER'])) $ref = $_SERVER['HTTP_REFERER'];
else $ref = 'Direct Link';
*/
class session {
	public $user_data = array();
	private $session_id = "";//sid
	private $session_rem = "";//session remember
	const cookiepath = "/";
	const cookiedomain = DOMAIN;
	const cookiesecure = 0;//Saugus sausainelis: Galima ijungti tik jeigu jusu HTTP serveris dirba su SSL
	
	public function prisijungti() {
		global $db, $_POST, $loginERROR;
		$result = $db->uzklausa("SELECT * FROM ".T_USERS." WHERE `username`='".$db->fix(trim($_POST['vartotojas']))."' AND `pass`='".md5(trim($_POST['slaptazodis']))."'",__FILE__,__LINE__);
		if ($db->num_rows($result) != 0) {
			$data = $db->masyvas($result);
			if ($data['active'] != 0) {
				$atsiminti = isset($_POST['atsiminti']) ? true : false;
				$db->uzklausa("DELETE  ".T_SESSIONS." WHERE `id`='".$this->session_id."'");
				$this->sukurti($data['user_id'], $atsiminti);
				$db->uzklausa("UPDATE  ".T_USERS." SET `lastlogin`='".time()."' WHERE `user_id`='".$data['user_id']."'");
			}
			sleep(1);
		} else {
			$db->uzklausa("INSERT INTO `".LENTELES_PRIESAGA."logai` SET `action`='Klaida prisijungiant: User: ".$db->fix($_POST['vartotojas'])." Pass: ".$db->fix($_POST['slaptazodis'])."', `time`='".time() ."', `ip`='".IP."'",__FILE__,__LINE__);
			$loginERROR = "Neteisingi duomenys!";
			sleep(3);
		}
		$db->free_result($result);
		return "";
	}
	public function atsijungti() {
		global $db, $_COOKIE;
/*
UPDATE phpbb2_sessions SET session_time = 1198943140, session_page = 0 WHERE session_id = 'c8411af062609b52d28bc21ab58a810a'
UPDATE phpbb2_users SET user_session_time = 1198943140, user_session_page = 0 WHERE user_id = 2
DELETE FROM phpbb2_sessions WHERE session_time < 1198939540 AND session_id <> 'c8411af062609b52d28bc21ab58a810a'
DELETE FROM phpbb2_sessions_keys WHERE last_login < 1197906340
*/
		$this->session_rem = isset($_COOKIE["mm_rem"]) ? $_COOKIE["mm_rem"] : "";
		$this->session_id = isset($_COOKIE["mm_sid"]) ? $_COOKIE["mm_sid"] : "";
	
		// Patikrinam ar $session_id nera kenksmingo kodo
		if (!preg_match("/^[A-Za-z0-9]*$/", $this->session_rem)) $this->session_rem = "";
		if (!preg_match("/^[A-Za-z0-9]*$/", $this->session_id)) $this->session_id = "";

		$result = $db->uzklausa("FROM ".T_SESSIONS." WHERE `id`='".$this->session_id."' AND `ip`='".IP."'");
		if ($db->num_rows($result) != 0) {
			$data = $db->masyvas($result);
			$db->uzklausa("UPDATE ".T_USERS." SET `lastvisit`=`".time()."` WHERE `user_id`='".(int) $data['user_id']."'");//Trūksta SELECT'o tam, kad sužinoti user_id

			$db->uzklausa("DELETE FROM ".T_SESSIONS." WHERE `id`='".$this->session_id."' AND `ip`='".IP."'");
			setcookie("mm_sid", '', time()-3600*24*30, self::cookiepath, self::cookiedomain, self::cookiesecure);
		
			if ($this->session_rem != "") {
				$db->uzklausa("DELETE FROM ".T_SESSIONS_KEYS." WHERE `key_id`='".$this->session_rem."'");
				setcookie("mm_rem", '', time()-3600*24*30, self::cookiepath, self::cookiedomain, self::cookiesecure);
			}
		}
		define("PRISIJUNGES", false);
		header("Location: ?");//prisijungti.phpPAGR_URL
	}

	public function sukurti($user_id = "", $atsiminti = false) {
		global $db;
		
		// Sugeneruojame session_id
		do {
			$this->session_id = md5(microtime());
			$rez = $db->uzklausa("SELECT * FROM ".T_SESSIONS." WHERE `id`='".$this->session_id."'");
			if ($db->num_rows($rez) == 0) $kartot = 0;
			else $kartot = 1;
		} while($kartot == 1);
		
		
		
		if ($user_id != "") {////// Vartotojui
			$db->uzklausa("INSERT INTO ".T_SESSIONS." SET `id`='".$this->session_id."', `user_id`='".(int) $user_id."', `pradzia`='".time()."', `dabar`='".time()."', `ip`='".IP."', `narsykle`='".$db->fix(NARSYKLE)."', `psl`='".$db->fix(PSL)."', `spaud`='1'");
			
			setcookie("mm_sid", $this->session_id, 0, self::cookiepath, self::cookiedomain, self::cookiesecure);//Galioja tol kol narsykle uzdaroma
			
			if ($atsiminti) {
				$db->uzklausa("INSERT INTO ".T_SESSIONS_KEYS." SET `key_id`='".$this->session_id."', `user_id`='".$user_id."', `ip`='".IP."', `narsykle`='".$db->fix(NARSYKLE)."'");
				
				setcookie("mm_rem", $this->session_id, time() + 3600*24*30, self::cookiepath, self::cookiedomain, self::cookiesecure);
				//if ($conf['max_autologin_time']) {
				//	$db->uzklausa('DELETE FROM '.T_SESSIONS_KEYS.'	WHERE last_logins<'.(time() - (86400 * (int) $conf['max_autologin_time'])));
				//}
			}
			define("PRISIJUNGES", false);
			header("Location: ?");//prisijungti.phpPAGR_URL

			return $this->user_data;
		} else {////// Svečiui
			$db->uzklausa("INSERT INTO ".T_SESSIONS." SET `id`='".$this->session_id."', `user_id`=1, `pradzia`=".time().", `dabar`=".time().", `ip`='".IP."', `narsykle`='".$db->fix(NARSYKLE)."', `psl`='".$db->fix(PSL)."', `spaud`=1");
			setcookie("mm_sid", $this->session_id, 0, self::cookiepath, self::cookiedomain, self::cookiesecure);//Galioja tol kol narsykle uzdaroma
			
			//Clean DB - Kiek ilgiausiai laiko gali tupėti svečių sesijos db
			$db->uzklausa("DELETE FROM `".T_SESSIONS."` WHERE `user_id`=1 AND `dabar`<'".(time() - (60*15))."'");

			define("PRISIJUNGES", false);
			return "";
		}
	}

	public function identifikuoti() {
		global $db, $_COOKIE;
		
		$this->user_data = "";
		
		$this->session_rem = isset($_COOKIE["mm_rem"]) ? $_COOKIE["mm_rem"] : "";
		$this->session_id = isset($_COOKIE["mm_sid"]) ? $_COOKIE["mm_sid"] : "";
		
		// Patikrinam ar nera kenksmingo kodo
		if (!preg_match("/^[A-Za-z0-9]*$/", $this->session_rem)) $this->session_rem = "";
		if (!preg_match("/^[A-Za-z0-9]*$/", $this->session_id)) $this->session_id = "";
		//$session_rem = md5($session_rem);
		//$session_id = md5($session_id);
		
		//
		// Kas yra: ar session_id ar session_rem ar nieko nera ir pagal tai atliekami atitinkami veiksmai
		//
		if (!empty($this->session_id)) {// Jeigu yra tik sesijos_ID tada tikrinam ar svecias ar vartotojas

			$user_info = $db->uzklausa("SELECT u.*, s.* FROM ".T_SESSIONS." s, ".T_USERS." u WHERE s.id='".$this->session_id."' AND s.user_id=u.user_id LIMIT 1");
			// Jei duombazėje yra toks pats session_id
			if($db->num_rows($user_info) == 1) {
				$this->user_data = $db->masyvas($user_info);
				
				if($this->user_data['narsykle'] == $db->fix(NARSYKLE) && $this->user_data['ip'] == IP) {//Jei sutampa naršyklės ir IP
					
					$db->uzklausa("UPDATE `".T_SESSIONS."` SET `dabar`='".time()."', `psl`='".$db->fix(PSL)."', `spaud`=`spaud`+1 WHERE `id`='".$this->session_id."'");
					if ($this->user_data['user_id'] != 1) {
					// Tai vartotojas
						define("PRISIJUNGES", true);
						return TRUE;
					} else {
						// yra session_id, bet tai svecias
						define("PRISIJUNGES", false);
						return "";//false buvo
					}
				} else {//Kažkas nesutampa (user_agent arba IP)
					if($this->user_data['ip'] == IP) {//Gal tiesiog atsinaujino naršyklę (nors ir tai tam prireiktų restartuoti naršyklę)
						//TODO: log
						$db->uzklausa("DELETE FROM `".T_SESSIONS."` WHERE `id`='".$this->session_id."' LIMIT 1");
						$this->sukurti();//Neatitinka naršyklė
					} else {
						//TODO: Būtinas log'as ir po to ban'as
					}
				}
			} else {
				$this->sukurti();
				// Tikriausiai bando atspeti sesija tad reiktu deti log ir po to gal net ir ban, aisku gali būti, kad sesija baigesi. TODO: log and ban
				return "";//false buvo
			}

			$db->free_result($user_info);

		} elseif (!empty($this->session_rem)) {
		//
		// Jeigu automatinis prisijungimas yra (jeigu nera buvimo sesijos ji sukuriama)
		//
			//Egzistuoja
			$rez = $db->uzklausa("SELECT u.*, s.* FROM ".T_SESSIONS_KEYS." s, ".T_USERS." u WHERE s.key_id='".$this->session_rem."' AND u.user_id=s.user_id AND s.ip='".IP."' AND s.narsykle='".$db->fix(NARSYKLE)."'");
			//Jeigu nera tokio sausainio...
			if($db->num_rows($rez) != 0) {
				$this->user_data = $db->masyvas($rez);
				
				//Jeigu nera buvimo sesijos ji sukuriama
				if ($this->session_id == "") {
					do {
						$this->session_id = md5(microtime());
						$rez = $db->uzklausa("SELECT * FROM ".T_SESSIONS." WHERE `id`='".$this->session_id."'");
						if ($db->num_rows($rez) == 0) {
							$kartoti = false;
						} else {
							$kartoti = true;
						}
					} while($kartoti == true);
			
					$db->uzklausa("INSERT INTO ".T_SESSIONS." SET `id`='".$this->session_id."', `user_id`='".$this->user_data['user_id']."', `pradzia`='".time()."', `dabar`='".time()."', `ip`='".IP."', `narsykle`='".$db->fix(NARSYKLE)."', `psl`='".$db->fix(PSL)."', `spaud`=1");
					setcookie("mm_sid", $this->session_id, 0, self::cookiepath, self::cookiedomain, self::cookiesecure);
				} else {
					// Atnaujinam
					$db->uzklausa("UPDATE ".T_SESSIONS." SET `dabar`='".time()."', `psl`='".$db->fix(PSL)."', `spaud`=`spaud`+1");
				}
				define("PRISIJUNGES", true);
				return TRUE;
				
			} else {
				// Gali buti bandymas atspeti ses_rem sausaini - TODO: registruoti bandymus ir ban IP
				return false;
			}
		} else {
		//
		// Jeigu is vis nieko nera
		//
			$this->sukurti();
			return "";
		}
	}

	public function isvalyti_mysql() {
		global $db;
		//global $conf;

		#### Kiek testavau - Duombaze neatsinaujina ####
		//$db->uzklausa("UPDATE ".T_USERS." u, ".T_SESSIONS." s SET u.lastvisit=s.dabar WHERE s.dabar<".(time() - (3600 * 5))." AND u.user_id=s.user_id AND s.user_id<>0");
		//$db->uzklausa("UPDATE ".T_USERS." SET u.lastvisit=s.dabar WHERE s.dabar<".(time() - (3600 * 5))." AND u.user_id=s.user_id AND s.user_id<>1");

		

		
		//$db->uzklausa("DELETE FROM ".T_SESSIONS." WHERE `dabar`<'".(time() - (3600 * 5))."'");
		
		/*

		*/
	}
}
?>
